<?php
namespace app\api\controller;

use app\common\controller\Api;
use OSS\OssClient;
use OSS\Core\OssException;
use app\common\exception\UploadException;
use app\common\library\Upload ;
use think\Config;

/**
 * 阿里云文件上传
 */
class Ossupload extends Api{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        // $this->check();
        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

        //检测删除文件或附件
        $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
            //如果设定为不备份则删除文件和记录 或 强制删除
            if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                if ($attachment && !empty($attachment['id'])) {
                    $attachment->delete();
                }
                if ($upload) {
                    //文件绝对路径
                    $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                    @unlink($filePath);
                }
            }
        };
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filesize = $this->request->post("filesize");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            $key = $this->request->post("key");
            $uploadId = $this->request->post("uploadId");

            if ($action == 'merge') {
                $attachment = null;
                $upload = null;
                //合并分片
                if ($config['uploadmode'] == 'server') {
                    //合并分片文件
                    try {
                        $upload = new Upload();
                        $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }

                $etags = $this->request->post("etags/a", []);
                if (count($etags) != $chunkcount) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("分片数据错误");
                }
                $listParts = [];
                for ($i = 0; $i < $chunkcount; $i++) {
                    $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
                }
                try {
                    $ret = $oss->completeMultipartUpload($config['bucket'], $key, $uploadId, $listParts);
                } catch (\Exception $e) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error($e->getMessage());
                }

                $result = json_decode(json_encode(simplexml_load_string($ret['body'], "SimpleXMLElement", LIBXML_NOCDATA)), true);
                if (!isset($result['Key'])) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("上传失败");
                } else {
                    $checkDeleteFile($attachment, $upload);
                    $this->success("上传成功", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
                }
            } else {
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                try {
                    //上传分片到OSS
                    $ret = $oss->uploadPart($config['bucket'], $key, $uploadId, ['fileUpload' => $file->getRealPath(), 'partNumber' => $chunkindex + 1]);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }


                $this->success("上传成功", "", [], 3, ['ETag' => $ret]);
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

            $url = $attachment->url;

            try {
                $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
                //成功不做任何操作
            } catch (\Exception $e) {
                $checkDeleteFile($attachment, $upload, true);
                $this->error("上传失败");
            }
            $checkDeleteFile($attachment, $upload);
//            $this->success("上传成功", ['url' => $url, 'fullurl' => cdnurl($url, true)]);
            $this->success("上传成功", ['url' => $url, 'fullurl' => config('api_image_url') . $url]);
        }
        return;

    }

    /**
     * 检查签名是否正确或过期
     */
    protected function check()
    {
        $aliosstoken = $this->request->post('aliosstoken', '', 'trim');
        if (!$aliosstoken) {
            $this->error("参数不正确");
        }
        $config = get_addon_config('alioss');
        list($accessKeyId, $sign, $data) = explode(':', $aliosstoken);
        if (!$accessKeyId || !$sign || !$data) {
            $this->error("参数不正确");
        }
        if ($accessKeyId !== $config['accessKeyId']) {
            $this->error("参数不正确");
        }
        if ($sign !== base64_encode(hash_hmac('sha1', base64_decode($data), $config['accessKeySecret'], true))) {
            $this->error("签名不正确");
        }
        $json = json_decode(base64_decode($data), true);
        if ($json['deadline'] < time()) {
            $this->error("请求已经超时");
        }
    }

    public function ossUploadFile(){
        require_once $_SERVER['DOCUMENT_ROOT'].'/../vendor/autoload.php';
        //dump(1212);
        $config = [
            'accessId'      => 'LTAI5tAn6aMvP2adPLsDa8eJ',
            'accessKey'     => '9HSoGgjlHukLtELYYvjewmOVe3H2f1',
            'bucket'        => '780g',
            'endpoint'      => 'https://oss-cn-zhangjiakou.aliyuncs.com',
            'host'          => 'https://780g.oss-cn-zhangjiakou.aliyuncs.com',
        ];

        $file = $_FILES['fileUp'];
        $type = explode('/' , $file['type']);
        $type = $type[count($type)-1];

        //储存到阿里云文件名
        $rand = mt_rand(10000,99999);
        $object = 'uploads'."/".date('Ymd' , time())."/".time().$rand.".".$type;

        //本地文件
        $filePath = $file['tmp_name'];

        try{
            $ossClient = new OssClient($config['accessId'], $config['accessKey'], $config['endpoint']);
            $result = $ossClient->uploadFile($config['bucket'] , $object , $filePath);
            $url = $result['info']['url'];
            $img = explode('com',$url);
            $img = $img[1];
            echo $img;

        }catch (OssException $e){
            // 失败记录错误查日志
            self::logs($e->getMessage(), 'oss');
            echo $e->getMessage();

        }
    }

    /**
     * 写日志
     * @param $data : 数据
     * @param $fileName : 写入哪个日志
     */
    public static function logs($data = null, $fileName = null)
    {
        if (is_null($data) || is_null($fileName)) {
            $out_arr['code'] = '400004';
            return $out_arr;
        }

        $path = RUNTIME_PATH . 'log/' . $fileName;

        if (!is_dir($path)) {
            $mkdir_re = mkdir($path, 0777, TRUE);
            if (!$mkdir_re) {
                self::logs($data, $fileName);
            }
        }

        $filePath = $path . "/" . date("Y-m-d", time());

        $time = date("Y-m-d H:i:s", time());
        $re   = file_put_contents($filePath, $time . " " . var_export($data, TRUE) . "\r\n\r\n", FILE_APPEND);

        if (!$re) {
            self::logs($data, $fileName);
        } else {
            $out_arr['code'] = '000000';
            return $out_arr;
        }
    }
}
?>
